package com.gcloud.mesh.asset.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gcloud.mesh.dcs.service.VoltageFmService;
import com.gcloud.mesh.framework.core.util.JsonUtil;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.cache.PermissionCodeCache;
import org.jeecg.common.constant.enums.SysLogOperateType;
import org.jeecg.common.constant.enums.SysLogType;
import org.jeecg.common.constant.enums.SysLogUrlOperate;
import org.jeecg.common.exception.ParamException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.LogUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.sm.SmManager;
import org.jeecg.common.vo.PermissionsInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.util.StringUtil;
import com.gcloud.framework.db.OperatorType;
import com.gcloud.framework.db.PageResult;
import com.gcloud.mesh.asset.dao.CloudResourceDao;
import com.gcloud.mesh.asset.dao.DatacenterDao;
import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.dao.NodeDao;
import com.gcloud.mesh.asset.dao.SwitcherDao;
import com.gcloud.mesh.asset.entity.CloudResourceEntity;
import com.gcloud.mesh.asset.entity.DatacenterEntity;
import com.gcloud.mesh.asset.entity.IaasEntity;
import com.gcloud.mesh.asset.entity.NodeEntity;
import com.gcloud.mesh.asset.entity.SwitcherEntity;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.asset.enums.MockType;
import com.gcloud.mesh.asset.enums.NetworkStatus;
import com.gcloud.mesh.asset.enums.PowerStatus;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.asset.sync.ISyncL2System;
import com.gcloud.mesh.asset.utils.supervisionsystem.ISupervisionSystem;
import com.gcloud.mesh.dcs.dao.AuthorityDao;
import com.gcloud.mesh.dcs.service.AuthorityService;
import com.gcloud.mesh.header.enums.ResourceSourceType;
import com.gcloud.mesh.header.enums.AuthorityResourceClassification;
import com.gcloud.mesh.header.enums.OrderType;
import com.gcloud.mesh.header.exception.AppErrorCode;
import com.gcloud.mesh.header.exception.AssetErrorCode;
import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.msg.asset.CreateDatacenterMsg;
import com.gcloud.mesh.header.msg.asset.CreateDeviceMsg;
import com.gcloud.mesh.header.msg.asset.CreateNodeMsg;
import com.gcloud.mesh.header.msg.asset.CreateNodeSmMsg;
import com.gcloud.mesh.header.msg.asset.CreateSwitcherMsg;
import com.gcloud.mesh.header.msg.asset.ListDatacenterMsg;
import com.gcloud.mesh.header.msg.asset.ListDeviceMsg;
import com.gcloud.mesh.header.msg.asset.UpdateDatacenterMsg;
import com.gcloud.mesh.header.msg.asset.UpdateDeviceMsg;
import com.gcloud.mesh.header.msg.asset.UpdateNodeMsg;
import com.gcloud.mesh.header.msg.asset.UpdateNodeSmMsg;
import com.gcloud.mesh.header.msg.asset.UpdateSwitcherMsg;
import com.gcloud.mesh.header.msg.dcs.ListByClassificationMsg;
import com.gcloud.mesh.header.vo.asset.CountDeviceVo;
import com.gcloud.mesh.header.vo.asset.DatacenterItemVo;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.header.vo.asset.MockIaasVo;
import com.gcloud.mesh.header.vo.asset.MockNodeVo;
import com.gcloud.mesh.header.vo.asset.MockSwitcherVo;
import com.gcloud.mesh.header.vo.asset.NodeItemVo;
import com.gcloud.mesh.header.vo.asset.SwitcherItemVo;
import com.gcloud.mesh.header.vo.dcs.AuthorityVo;
import com.gcloud.mesh.redis.MockRedis;
import com.gcloud.mesh.sm.service.SmService;
import com.gcloud.mesh.threads.ThreadManager;
import com.gcloud.mesh.utils.TimestampUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AssetServiceImpl implements IAssetService {

	private static final String PERFORMANCE = "performance";

	private static final String SM_TOKEN = "sm-token";

	private boolean isPerformance = false;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private IaasDao iaasDao;

	@Autowired
	private DatacenterDao datacenterDao;

	@Autowired
	private NodeDao nodeDao;

	@Autowired
	private SwitcherDao switcherDao;

	@Autowired
	private CloudResourceDao cloudResourceDao;
	
	@Autowired
	private AuthorityDao authorityDao;

	@Autowired
	private AuthorityService authorityService;

	@Autowired
	private MockRedis<MockIaasVo> mockIaasRedis;

	@Autowired
	private MockRedis<MockNodeVo> mockNodeRedis;

	@Autowired
	private MockRedis<MockSwitcherVo> mockSwitcherRedis;

	@Autowired
	private SmService smService;

	@Autowired
	private VoltageFmService voltageFmService;

	@Autowired
	private ISysBaseAPI sysBaseAPI;
	
	@Autowired
	private ISupervisionSystem supervision;
	
	@Autowired
	private ISyncL2System syncL2System;

	private Map<String, String> datacenterNameMap = new HashMap<String, String>();

	private Map<String, DatacenterItemVo> datacenterMap = new ConcurrentHashMap<String, DatacenterItemVo>();
	
	private Map<Integer, Boolean> authorityMap = new ConcurrentHashMap<Integer, Boolean>();

	private List<DeviceItemVo> performanceDevices = null;

	@Override
	public String createDevice(CreateDeviceMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
//		if (isPerformance) {
//			// 高性能模式
//			IaasEntity iaas = new IaasEntity();
//			iaas.setId(UUID.randomUUID().toString());
//			iaas.setName(msg.getName());
//			iaas.setType(msg.getType());
//			iaas.setEsn(msg.getEsn());
//			iaas.setDatacenterId(msg.getDatacenterId());
//			iaas.setCreator(userId);
//			iaas.setCreateTime(new Date());
//			iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
//			iaas.setDeviceModel(msg.getDeviceModel());
//			iaas.setFrom(ResourceSourceType.MANUAL.getName());
//			try {
//				iaasDao.save(iaas);
//			} catch (BaseException e) {
//				log.error("数据库保存失败", e.getMessage());
//				throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
//			}
//			ThreadManager.submit(new Runnable() {
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//					try {
//						iaasDao.save(iaas);
//					} catch (BaseException e) {
//						log.error("数据库保存失败", e.getMessage());
//						throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
//					}
//				}
//
//			});
//			return iaas.getId();
//		} else {
			IaasEntity iaas = null;
			Map<String, Object> props = new HashMap<String, Object>();
			props.put("type", msg.getType());
			props.put("name", msg.getName());
			List<IaasEntity> iaass = iaasDao.findByProperties(props);
			for (IaasEntity iaasdb : iaass) {
				if (iaasdb != null && iaasdb.getName().equals(msg.getName())) {
					throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
				}
			}

			if (DeviceType.getDeviceTypeByNo(msg.getType()) == null) {
				throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
			}
			if (DeviceType.SERVER.getNo() == msg.getType() || DeviceType.SWITCHER.getNo() == msg.getType()) {
				throw new ParamException(AssetErrorCode.RESOURSE_TYPE_ERROR);
			}
			DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
			if (dc == null) {
				throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
			}
			iaas = new IaasEntity();
			iaas.setId(UUID.randomUUID().toString());
			iaas.setName(msg.getName());
			iaas.setType(msg.getType());
			iaas.setEsn(msg.getEsn());
			iaas.setDatacenterId(msg.getDatacenterId());
			iaas.setCreator(userId);
			iaas.setCreateTime(new Date());
			iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
			iaas.setDeviceModel(msg.getDeviceModel());
			iaas.setVisible(true);

			if (StringUtils.isBlank(msg.getFrom())) {
				iaas.setFrom(ResourceSourceType.MANUAL.getName());
			} else {
				// iaas.setFrom(msg.getFrom());
				iaas.setFrom(ResourceSourceType.SYNC.getName());
			}
			if (StringUtils.isNotBlank(msg.getDeviceId())) {
				iaas.setDeviceId(msg.getDeviceId());
			}

			try {
				iaasDao.save(iaas);
			} catch (BaseException e) {
				log.error("数据库保存失败", e.getMessage());
				throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
			}
			return iaas.getId();
//		}

		// TODO 新增模拟数据
		// MockIaasVo mockVo = new MockIaasVo();
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockIaasRedis.set(mockVo.getId(), MockType.IAAS, mockVo);

	}

	@Override
	public String updateDevice(UpdateDeviceMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		IaasEntity iaas = iaasDao.getById(msg.getId(), userId);
		if (iaas == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
		}
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("type", msg.getType());
		props.put("name", msg.getName());
		if (!iaas.getName().equals(msg.getName())) {
			List<IaasEntity> iaasdbs = iaasDao.findByProperties(props);
			for (IaasEntity iaasdb : iaasdbs) {
				if (iaasdb != null && iaasdb.getName().equals(msg.getName())) {
					if (!msg.getId().equals(iaasdb.getId())) {
						throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
					}
				}
			}
		}
		if (iaas.getFrom() == ResourceSourceType.SYNC.getName()) {
			throw new ParamException(AssetErrorCode.RESOURSE_SYNC_NOT_UPDATE);
		}
		if (msg.getType() != null && DeviceType.getDeviceTypeByNo(msg.getType()) == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_TYPE_ERROR);
		}
		if (msg.getDatacenterId() != null) {
			DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
			if (dc == null) {
				throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
			}
		}

		List<String> updateFields = new ArrayList<String>();
		if (msg.getName() != null) {
			updateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getEsn() != null) {
			updateFields.add("esn");
			iaas.setEsn(msg.getEsn());
		}
		if (msg.getDeviceManufacturer() != null) {
			updateFields.add("device_manufacturer");
			iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
		}
		if (msg.getDeviceModel() != null) {
			updateFields.add("device_model");
			iaas.setDeviceModel(msg.getDeviceModel());
		}
		if (msg.getType() != null) {
			updateFields.add("type");
			iaas.setType(msg.getType());
		}
		if (msg.getDatacenterId() != null) {
			updateFields.add("datacenter_id");
			iaas.setDatacenterId(msg.getDatacenterId());
		}

		try {
			iaasDao.update(iaas, updateFields);
		} catch (BaseException e) {
			log.error("数据库更新失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_UPDATE);
		}

		// TODO 修改模拟数据
		// MockIaasVo mockVo = new MockIaasVo();
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockIaasRedis.set(iaas.getId(), MockType.IAAS, mockVo);

		return iaas.getId();
	}

	@Override
	public PageResult<DeviceItemVo> pageDevice(int pageNum, int pageSize, Integer type, String name, String userId)
			throws BaseException {
		// TODO Auto-generated method stub
		return pageDevice(pageNum, pageSize, null, type, name, userId);
	}

	@Override
	public PageResult<DeviceItemVo> pageDevice(int pageNum, int pageSize, String datacenterId, Integer type,
			String name, String userId) throws BaseException {
		// TODO Auto-generated method stub
		PageResult<DeviceItemVo> result = new PageResult<DeviceItemVo>();

		PageResult<DeviceItemVo> iaases = null;
//		if (isPerformance) {
			// 高性能模式
			// if (performanceDevices == null) {
			iaases = iaasDao.page(pageNum, pageSize, datacenterId, name, type, null, DeviceItemVo.class);
			for (DeviceItemVo vo : iaases.getList()) {
				vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
				vo.setDatacenterName(datacenterNameMap.get(vo.getDatacenterId()));
			}
			result.setList(iaases.getList());
			result.setPageNo(iaases.getPageNo());
			result.setPageSize(iaases.getPageSize());
			result.setTotalCount(iaases.getTotalCount());
			// }else {
			// result.setList(performanceDevices);
			// result.setPageNo(pageNum);
			// result.setPageSize(pageSize);
			// result.setTotalCount(performanceDevices.size());
			// }
//		} else {
//			if (type != null && DeviceType.getDeviceTypeByNo(type) == null) {
//				throw new ParamException(AssetErrorCode.RESOURSE_TYPE_NOT_EXIST);
//			}
//			iaases = iaasDao.pageDevice(pageNum, pageSize, datacenterId, name, type);
//			if (iaases != null) {
//				for (DeviceItemVo vo : iaases.getList()) {
//					vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
//					vo.setDatacenterName(datacenterNameMap.get(vo.getDatacenterId()));
//				}
//				result.setList(iaases.getList());
//				result.setPageNo(iaases.getPageNo());
//				result.setPageSize(iaases.getPageSize());
//				result.setTotalCount(iaases.getTotalCount());
//			}
//		}

		return result;
	}

	@Override
	public DeviceItemVo detailDevice(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		// 判断是不是管理员
		IaasEntity iaas = iaasDao.getById(id, userId);
		DeviceItemVo vo = new DeviceItemVo();
		if (iaas == null) {
			// throw new BaseException(AssetErrorCode.RESOURSE_NO_AUTH);
			log.info("[AssetServiceImpl][detailDevice] 资源【{}】不存在!", id);
		} else {
			BeanUtils.copyProperties(iaas, vo);
			vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
		}

		return vo;
	}

	@Override
	public IaasEntity deleteDevice(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		IaasEntity iaas = iaasDao.getById(id, userId);
		if (iaas == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
		}

		try {
			iaasDao.deleteById(iaas.getId());
		} catch (BaseException e) {
			log.error("资源删除失败");
			throw new BaseException(AssetErrorCode.RESOURSE_DB_DELETE);
		}

		// TODO 删除模拟数据
		// String key = String.format("mesh_controller_mock_type_%d_id_%s",
		// MockType.IAAS.getType(), iaas.getId());
		// mockIaasRedis.delete(key);

		return iaas;
	}

	@Transactional
	@Override
	public String createNode(CreateNodeSmMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("name", msg.getName());
		props.put("type", DeviceType.SERVER.getNo());
		List<IaasEntity> iaass = iaasDao.findByProperties(props);
		for (IaasEntity iaas : iaass) {
			if (iaas != null && iaas.getName().equals(msg.getName())) {
				throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
			}
		}
		DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
		if (dc == null) {
			throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
		}

		IaasEntity iaas = new IaasEntity();
		iaas.setId(UUID.randomUUID().toString());
		iaas.setName(msg.getName());
		iaas.setType(DeviceType.SERVER.getNo());
		iaas.setEsn(msg.getEsn());
		iaas.setDatacenterId(msg.getDatacenterId());
		iaas.setCreator(userId);
		iaas.setCreateTime(new Date());

		String deviceId = UUID.randomUUID().toString();
		iaas.setDeviceId(deviceId);
		iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
		iaas.setDeviceModel(msg.getDeviceModel());
		iaas.setFrom(ResourceSourceType.MANUAL.getName());
		iaas.setVisible(true);

		NodeEntity node = new NodeEntity();
		node.setId(deviceId);
		node.setMgmIp(msg.getMgmIp());
		node.setIpmiIp(msg.getIpmiIp());
		node.setIpmiUser(msg.getIpmiUser());

		node.setNetworkStatus(NetworkStatus.ONLINE.getNo());
		node.setPowerStatus(PowerStatus.RUNNING.getNo());
		node.setHostname(msg.getHostname());
		node.setSmData(msg.getSmData());

		// 默认设值
		node.setPowerConsumption(0f);
		node.setEnergyEfficiencyRatio(0f);
		node.setStorageCapacity(0f);
		node.setIsolation(false);

		node.setCabinetId(msg.getCabinetId());
		
		try {
			iaasDao.save(iaas);
			nodeDao.save(node);
		} catch (BaseException e) {
			log.error("数据库保存失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
		}
		// TODO 新增模拟数据
		// MockNodeVo mockVo = new MockNodeVo();
		// BeanUtils.copyProperties(node, mockVo);
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockNodeRedis.set("node_" + mockVo.getId(), MockType.IT_DEVICE,
		// mockVo);
		return iaas.getId();
	}

	@Transactional
	@Override
	public String updateNode(UpdateNodeSmMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		NodeItemVo nodeVo = nodeDao.getById(msg.getId(), null, NodeItemVo.class);
		if (nodeVo == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("name", msg.getName());
		props.put("type", DeviceType.SERVER.getNo());
		if (!nodeVo.getName().equals(msg.getName())) {
			List<IaasEntity> iaasdbs = iaasDao.findByProperties(props);
			for (IaasEntity iaasdb : iaasdbs) {
				if (iaasdb != null && iaasdb.getName().equals(msg.getName())) {
					if (!msg.getId().equals(iaasdb.getId())) {
						throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
					}
				}
			}
		}

		if (nodeVo.getFrom() == ResourceSourceType.SYNC.getName()) {
			throw new ParamException(AssetErrorCode.RESOURSE_SYNC_NOT_UPDATE);
		}
		if (msg.getDatacenterId() != null && datacenterDao.getById(msg.getDatacenterId()) == null) {
			throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
		}

		List<String> iaasUpdateFields = new ArrayList<String>();
		List<String> nodeUpdateFields = new ArrayList<String>();
		IaasEntity iaas = new IaasEntity();
		BeanUtils.copyProperties(nodeVo, iaas);
		if (msg.getName() != null) {
			iaasUpdateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getEsn() != null) {
			iaasUpdateFields.add("esn");
			iaas.setEsn(msg.getEsn());
		}
		if (msg.getDeviceManufacturer() != null) {
			iaasUpdateFields.add("device_manufacturer");
			iaas.setDatacenterId(msg.getDatacenterId());
		}
		if (msg.getDeviceModel() != null) {
			iaasUpdateFields.add("device_model");
			iaas.setDeviceModel(msg.getDeviceModel());
		}
		if (msg.getDatacenterId() != null) {
			iaasUpdateFields.add("datacenter_id");
			iaas.setDatacenterId(msg.getDatacenterId());
		}
		NodeEntity node = new NodeEntity();
		BeanUtils.copyProperties(nodeVo, node);
		node.setId(nodeVo.getDeviceId());
		if (msg.getName() != null) {
			iaasUpdateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getMgmIp() != null) {
			nodeUpdateFields.add("mgm_ip");
			node.setMgmIp(msg.getMgmIp());
		}
		if (msg.getIpmiIp() != null) {
			nodeUpdateFields.add("ipmi_ip");
			node.setIpmiIp(msg.getIpmiIp());
		}
		if (msg.getIpmiUser() != null) {
			nodeUpdateFields.add("ipmi_user");
			node.setIpmiUser(msg.getIpmiUser());
		}
		if (msg.getRatedPowerSm() != null) {
			nodeUpdateFields.add("rated_power_sm");
			node.setRatedPowerSm(msg.getRatedPowerSm());
		}
		if (msg.getRatedVoltageSm() != null) {
			nodeUpdateFields.add("rated_voltage_sm");
			node.setRatedVoltageSm(msg.getRatedVoltageSm());
		}
		if (msg.getEnergyEfficiencyRatio() != null) {
			nodeUpdateFields.add("energy_efficiency_ratio");
			node.setEnergyEfficiencyRatio(msg.getEnergyEfficiencyRatio());
		}
		if (msg.getStorageCapacity() != null) {
			nodeUpdateFields.add("storage_capacity");
			node.setStorageCapacity(msg.getStorageCapacity());
		}
		if (msg.getPowerConsumption() != null) {
			nodeUpdateFields.add("power_consumption");
			node.setPowerConsumption(msg.getPowerConsumption());
		}
		if (msg.getIsolation() != null) {
			nodeUpdateFields.add("isolation");
			node.setIsolation(msg.getIsolation());
		}
		if (msg.getHostname() != null) {
			nodeUpdateFields.add("hostname");
			node.setHostname(msg.getHostname());
		}
		if (msg.getSmData() != null) {
			nodeUpdateFields.add("sm_data");
			node.setSmData(msg.getSmData());
		}

		try {
			if (iaasUpdateFields.size() > 0) {
				iaasDao.update(iaas, iaasUpdateFields);
			}
			if (nodeUpdateFields.size() > 0) {
				nodeDao.update(node, nodeUpdateFields);
			}
		} catch (BaseException e) {
			log.error("数据库更新失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_UPDATE);
		}

		// TODO 新增模拟数据
		// MockNodeVo mockVo = new MockNodeVo();
		// BeanUtils.copyProperties(node, mockVo);
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockNodeRedis.set("node_" + mockVo.getId(), MockType.IT_DEVICE,
		// mockVo);
		return nodeVo.getId();
	}

	@Transactional
	@Override
	public String updateNode(UpdateNodeMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		NodeItemVo nodeVo = nodeDao.getById(msg.getId(), null, NodeItemVo.class);
		if (nodeVo == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("name", msg.getName());
		props.put("type", DeviceType.SERVER.getNo());
		if (!nodeVo.getName().equals(msg.getName())) {
			List<IaasEntity> iaasdbs = iaasDao.findByProperties(props);
			for (IaasEntity iaasdb : iaasdbs) {
				if (iaasdb != null && iaasdb.getName().equals(msg.getName())) {
					if (!msg.getId().equals(iaasdb.getId())) {
						throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
					}
				}
			}
		}

		if (nodeVo.getFrom() == ResourceSourceType.SYNC.getName()) {
			throw new ParamException(AssetErrorCode.RESOURSE_SYNC_NOT_UPDATE);
		}
		if (msg.getDatacenterId() != null && datacenterDao.getById(msg.getDatacenterId()) == null) {
			throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
		}

		List<String> iaasUpdateFields = new ArrayList<String>();
		List<String> nodeUpdateFields = new ArrayList<String>();
		IaasEntity iaas = new IaasEntity();
		BeanUtils.copyProperties(nodeVo, iaas);
		if (msg.getName() != null) {
			iaasUpdateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getEsn() != null) {
			iaasUpdateFields.add("esn");
			iaas.setEsn(msg.getEsn());
		}
		if (msg.getDeviceManufacturer() != null) {
			iaasUpdateFields.add("device_manufacturer");
			iaas.setDatacenterId(msg.getDatacenterId());
		}
		if (msg.getDeviceModel() != null) {
			iaasUpdateFields.add("device_model");
			iaas.setDeviceModel(msg.getDeviceModel());
		}
		if (msg.getDatacenterId() != null) {
			iaasUpdateFields.add("datacenter_id");
			iaas.setDatacenterId(msg.getDatacenterId());
		}
		NodeEntity node = new NodeEntity();
		BeanUtils.copyProperties(nodeVo, node);
		node.setId(nodeVo.getDeviceId());
		if (msg.getName() != null) {
			iaasUpdateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getMgmIp() != null) {
			nodeUpdateFields.add("mgm_ip");
			node.setMgmIp(msg.getMgmIp());
		}
		if (msg.getIpmiIp() != null) {
			nodeUpdateFields.add("ipmi_ip");
			node.setIpmiIp(msg.getIpmiIp());
		}
		if (msg.getIpmiUser() != null) {
			nodeUpdateFields.add("ipmi_user");
			node.setIpmiUser(msg.getIpmiUser());
		}
		if (msg.getRatedPowerSm() != null) {
			nodeUpdateFields.add("rated_power_sm");
			node.setRatedPowerSm(msg.getRatedPowerSm());
		}
		if (msg.getRatedVoltageSm() != null) {
			nodeUpdateFields.add("rated_voltage_sm");
			node.setRatedVoltageSm(msg.getRatedVoltageSm());
		}
		if (msg.getEnergyEfficiencyRatio() != null) {
			nodeUpdateFields.add("energy_efficiency_ratio");
			node.setEnergyEfficiencyRatio(msg.getEnergyEfficiencyRatio());
		}
		if (msg.getStorageCapacity() != null) {
			nodeUpdateFields.add("storage_capacity");
			node.setStorageCapacity(msg.getStorageCapacity());
		}
		if (msg.getPowerConsumption() != null) {
			nodeUpdateFields.add("power_consumption");
			node.setPowerConsumption(msg.getPowerConsumption());
		}
		if (msg.getIsolation() != null) {
			nodeUpdateFields.add("isolation");
			node.setIsolation(msg.getIsolation());
		}
		if (msg.getHostname() != null) {
			nodeUpdateFields.add("hostname");
			node.setHostname(msg.getHostname());
		}

		try {
			if (iaasUpdateFields.size() > 0) {
				iaasDao.update(iaas, iaasUpdateFields);
			}
			if (nodeUpdateFields.size() > 0) {
				nodeDao.update(node, nodeUpdateFields);
			}
		} catch (BaseException e) {
			log.error("数据库更新失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_UPDATE);
		}

		return nodeVo.getId();
	}

	@Override
	public NodeItemVo detailNode(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		NodeItemVo node = nodeDao.getById(id, null, NodeItemVo.class);
		if (node == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		DeviceType deviceType = DeviceType.getDeviceTypeByNo(node.getType());
		if (deviceType != null) {
			node.setTypeCnName(deviceType.getCnName());
		}
		node.setTypeCnName(DeviceType.getDeviceTypeByNo(node.getType()).getCnName());

		return node;

	}

	@Override
	public PageResult<NodeItemVo> pageNode(int pageNum, int pageSize, String name, String order, String userId)
			throws BaseException {
		// TODO Auto-generated method stub

		return pageNode(pageNum, pageSize, null, name, order, userId);
	}

	@Override
	public PageResult<NodeItemVo> pageNode(int pageNum, int pageSize, String datacenterId, String name, String order,
			String userId) throws BaseException {
		// TODO Auto-generated method stub
		if (!StringUtils.isBlank(order) && OrderType.getByName(order) == null) {
			throw new ParamException(AssetErrorCode.ORDER_FORMAT_ERROR);
		}

		PageResult<NodeItemVo> nodes = nodeDao.page(pageNum, pageSize, datacenterId, name, order, userId,
				NodeItemVo.class);
		for (NodeItemVo vo : nodes.getList()) {
			// vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
			// vo.setNetworkStatusCnName(NetworkStatus.getStatusByNo(vo.getNetworkStatus()).getCnName());
			// vo.setPowerStatusCnName(PowerStatus.getStatusByNo(vo.getPowerStatus()).getCnName());
			DeviceType type = DeviceType.getDeviceTypeByNo(vo.getType());
			vo.setDatacenterName(datacenterNameMap.get(vo.getDatacenterId()));
			if (type != null) {
				vo.setTypeCnName(type.getCnName());
			}
			if (vo.getNetworkStatus() != null) {
				NetworkStatus networkStatus = NetworkStatus.getStatusByNo(vo.getNetworkStatus());
				if (networkStatus != null) {
					vo.setNetworkStatusCnName(networkStatus.getCnName());
				}
			}
			PowerStatus powerStatus = PowerStatus.getStatusByNo(vo.getPowerStatus());
			if (powerStatus != null) {
				vo.setPowerStatusCnName(powerStatus.getCnName());
			}

		}
		PageResult<NodeItemVo> result = new PageResult<NodeItemVo>();
		result.setList(nodes.getList());
		result.setPageNo(nodes.getPageNo());
		result.setPageSize(nodes.getPageSize());
		result.setTotalCount(nodes.getTotalCount());
		return result;
	}

	@Transactional
	@Override
	public String createSwitcher(CreateSwitcherMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		Map<String, Object> props = new HashMap<String, Object>();
		props.put("name", msg.getName());
		props.put("type", DeviceType.SWITCHER.getNo());
		List<IaasEntity> iaass = iaasDao.findByProperties(props);
		for (IaasEntity iaas : iaass) {
			if (iaas != null && iaas.getName().equals(msg.getName())) {
				throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
			}
		}
		DatacenterEntity dc = datacenterDao.getById(msg.getDatacenterId());
		if (dc == null) {
			throw new ParamException(AssetErrorCode.DATACENTER_NOT_EXIST);
		}

		IaasEntity iaas = new IaasEntity();
		iaas.setId(UUID.randomUUID().toString());
		iaas.setName(msg.getName());
		iaas.setType(DeviceType.SWITCHER.getNo());
		iaas.setEsn(msg.getEsn());
		iaas.setDatacenterId(msg.getDatacenterId());
		iaas.setCreator(userId);
		iaas.setCreateTime(new Date());
		String deviceId = UUID.randomUUID().toString();
		iaas.setDeviceId(deviceId);
		iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
		iaas.setDeviceModel(msg.getDeviceModel());
		iaas.setFrom(ResourceSourceType.MANUAL.getName());
		iaas.setVisible(true);

		SwitcherEntity switcher = new SwitcherEntity();
		switcher.setId(deviceId);
		switcher.setIp(msg.getIp());
		switcher.setStatus(NetworkStatus.ONLINE.getNo());
		switcher.setCommunity(msg.getCommunity());
		switcher.setCabinetId(msg.getCabinetId());

		try {
			iaasDao.save(iaas);
			switcherDao.save(switcher);
		} catch (BaseException e) {
			log.error("数据库保存失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
		}

		// TODO 新增模拟数据
		// MockSwitcherVo mockVo = new MockSwitcherVo();
		// BeanUtils.copyProperties(switcher, mockVo);
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockSwitcherRedis.set("switcher_" + mockVo.getId(),
		// MockType.IT_DEVICE, mockVo);
		return iaas.getId();
	}

	@Transactional
	@Override
	public String updateSwitcher(UpdateSwitcherMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		SwitcherItemVo switcherVo = switcherDao.getById(msg.getId(), null, SwitcherItemVo.class);
		if (switcherVo == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		if (!switcherVo.getName().equals(msg.getName())) {
			Map<String, Object> props = new HashMap<String, Object>();
			props.put("name", msg.getName());
			props.put("type", DeviceType.SWITCHER.getNo());
			List<IaasEntity> iaasdbs = iaasDao.findByProperties(props);
			for (IaasEntity iaasdb : iaasdbs) {
				if (iaasdb != null && iaasdb.getName().equals(msg.getName())) {
					if (!msg.getId().equals(iaasdb.getId())) {
						throw new ParamException(AssetErrorCode.DEVICE_NAME_EXIST);
					}
				}
			}
		}

		if (switcherVo.getFrom() == ResourceSourceType.SYNC.getName()) {
			throw new ParamException(AssetErrorCode.RESOURSE_SYNC_NOT_UPDATE);
		}
		if (msg.getDatacenterId() != null && datacenterDao.getById(msg.getDatacenterId()) == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_TYPE_NOT_EXIST);
		}

		List<String> iaasUpdateFields = new ArrayList<String>();
		List<String> switcherUpdateFields = new ArrayList<String>();
		IaasEntity iaas = new IaasEntity();
		BeanUtils.copyProperties(switcherVo, iaas);
		if (msg.getName() != null) {
			iaasUpdateFields.add("name");
			iaas.setName(msg.getName());
		}
		if (msg.getEsn() != null) {
			iaasUpdateFields.add("esn");
			iaas.setEsn(msg.getEsn());
		}
		if (msg.getDeviceManufacturer() != null) {
			iaasUpdateFields.add("device_manufacturer");
			iaas.setDeviceManufacturer(msg.getDeviceManufacturer());
		}
		if (msg.getDeviceModel() != null) {
			iaasUpdateFields.add("device_model");
			iaas.setDeviceModel(msg.getDeviceModel());
		}
		if (msg.getDatacenterId() != null) {
			iaasUpdateFields.add("datacenter_id");
			iaas.setDatacenterId(msg.getDatacenterId());
		}
		SwitcherEntity switcher = new SwitcherEntity();
		BeanUtils.copyProperties(switcherVo, switcher);
		switcher.setId(switcherVo.getDeviceId());
		if (msg.getIp() != null) {
			switcherUpdateFields.add("ip");
			switcher.setIp(msg.getIp());
		}
		if (msg.getCommunity() != null) {
			switcherUpdateFields.add("community");
			switcher.setCommunity(msg.getCommunity());
		}

		try {
			if (iaasUpdateFields.size() > 0) {
				iaasDao.update(iaas, iaasUpdateFields);
			}
			if (switcherUpdateFields.size() > 0) {
				switcherDao.update(switcher, switcherUpdateFields);
			}
		} catch (BaseException e) {
			log.error("数据库更新失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_UPDATE);
		}
		// TODO 新增模拟数据
		// MockSwitcherVo mockVo = new MockSwitcherVo();
		// BeanUtils.copyProperties(switcher, mockVo);
		// BeanUtils.copyProperties(iaas, mockVo);
		// mockSwitcherRedis.set("switcher_" + mockVo.getId(),
		// MockType.IT_DEVICE, mockVo);
		return switcherVo.getId();
	}

	@Override
	public SwitcherItemVo detailSwitcher(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		SwitcherItemVo switcher = switcherDao.getById(id, null, SwitcherItemVo.class);
		if (switcher == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		switcher.setTypeCnName(DeviceType.getDeviceTypeByNo(switcher.getType()).getCnName());

		return switcher;
	}

	@Override
	public PageResult<SwitcherItemVo> pageSwitcher(int pageNum, int pageSize, String name, String userId)
			throws BaseException {
		// TODO Auto-generated method stub
		PageResult<SwitcherItemVo> switchers = switcherDao.page(pageNum, pageSize, name, userId, SwitcherItemVo.class);
		for (SwitcherItemVo vo : switchers.getList()) {
			vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
			vo.setStatusCnName(PowerStatus.getStatusByNo(vo.getStatus()).getCnName());
		}
		PageResult<SwitcherItemVo> result = new PageResult<SwitcherItemVo>();
		result.setList(switchers.getList());
		result.setPageNo(switchers.getPageNo());
		result.setPageSize(switchers.getPageSize());
		result.setTotalCount(switchers.getTotalCount());
		return result;
	}

	@Override
	public String createDatacenter(CreateDatacenterMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		DatacenterEntity dc = datacenterDao.findUniqueByProperty("name", msg.getName());
		if (dc != null && dc.getName().equals(dc.getName())) {
			throw new ParamException(AssetErrorCode.RESOURSE_NAME_EXIST);
		}

		dc = new DatacenterEntity();
		dc.setId(UUID.randomUUID().toString());
		dc.setName(msg.getName());
		dc.setIp(msg.getIp());
		dc.setCreator(userId);
		dc.setPowerConservation(false);
		dc.setCreateTime(new Date());
		dc.setStructure(msg.getStructure());
		dc.setRooms(msg.getRooms());
		try {
			datacenterDao.save(dc);
		} catch (BaseException e) {
			log.error("数据库保存失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_SAVE);
		}
		return dc.getId();
	}

	@Override
	public String updateDatacenter(UpdateDatacenterMsg msg, String userId) throws BaseException {
		// TODO Auto-generated method stub
		DatacenterEntity dc = datacenterDao.getById(msg.getId(), userId);
		if (dc == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
		}

		List<String> updateFields = new ArrayList<String>();
		if (msg.getName() != null) {
			if (datacenterDao.findUniqueByProperty("name", msg.getName()) != null) {
				throw new ParamException(AssetErrorCode.RESOURSE_NAME_EXIST);
			} else {
				updateFields.add("name");
				dc.setName(msg.getName());
			}
		}
		if (msg.getIp() != null) {
			updateFields.add("ip");
			dc.setIp(msg.getIp());
		}
		if (msg.getPower() != null) {
			updateFields.add("power");
			dc.setPower(msg.getPower());
		}
		if (msg.getPowerConservation() != null) {
			updateFields.add("power_conservation");
			dc.setPowerConservation(msg.getPowerConservation());
		}
		if (msg.getThreshold() != null) {
			updateFields.add("threshold");
			dc.setThreshold(msg.getThreshold());
		}
		if(StringUtils.isNotBlank(msg.getStructure())) {
			updateFields.add("structure");
			dc.setStructure(msg.getStructure());
		}
		try {
			datacenterDao.update(dc, updateFields);
		} catch (BaseException e) {
			log.error("数据库更新失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_UPDATE);
		}
		return dc.getId();
	}

	@Override
	public PageResult<DatacenterItemVo> pageDatacenter(int pageNum, int pageSize, String id, String name, String ip,
			String userId, Boolean hasNode) throws BaseException {
		PageResult<DatacenterItemVo> result = new PageResult<DatacenterItemVo>();
//		if (isPerformance) {
//			List<DatacenterItemVo> list = new ArrayList<DatacenterItemVo>(datacenterMap.values());
//			result.setList(list);
//			result.setPageNo(pageNum);
//			result.setPageSize(pageSize);
//			result.setTotalCount(list.size());
//		} else {
			result = datacenterDao.page(pageNum, pageSize, id, name, ip, userId, hasNode, DatacenterItemVo.class);
//		}

		return result;
	}

	@Override
	public PageResult<DatacenterItemVo> pageDatacenter(int pageNum, int pageSize, String id, String name, String ip,
			String userId) throws BaseException {
		PageResult<DatacenterItemVo> result = datacenterDao.page(pageNum, pageSize, id, name, ip, userId, null,
				DatacenterItemVo.class);
		return result;
	}

	@Override
	public DatacenterItemVo detailDatacenter(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		DatacenterEntity dc = datacenterDao.getById(id, userId);
		if (dc == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}
		DatacenterItemVo vo = new DatacenterItemVo();
		BeanUtils.copyProperties(dc, vo);

		return vo;
	}

	@Override
	public String deleteDatacenter(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub

		DatacenterEntity dc = datacenterDao.getById(id, userId);
		if (dc == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NO_AUTH);
		}

		List<IaasEntity> iaases = iaasDao.findByProperty("datacenter_id", id);
		if (iaases.size() > 0) {
			throw new BaseException(AssetErrorCode.DATACENTER_IS_USING);
		}
		try {
			datacenterDao.deleteById(id);
		} catch (BaseException e) {
			log.error("资源删除失败", e.getMessage());
			throw new BaseException(AssetErrorCode.RESOURSE_DB_DELETE);
		}

		return id;
	}

	@Transactional
	@Override
	public IaasEntity deleteNode(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		IaasEntity iaas = iaasDao.getById(id, userId);
		if (iaas == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
		}

		// 判断是否存在虚拟机资源
		List<CloudResourceEntity> clouds = cloudResourceDao.findAll();
		CloudResourceEntity cloud = clouds.stream().filter(s -> {
			boolean res = false;
			try {
				JSONObject json = (JSONObject) JSONObject.parse(s.getExpand());
				if (!json.isEmpty()) {
					String nodeId = json.getString("nodeId");
					if (id.equals(nodeId)) {
						res = true;
					}
				}
			} catch (Exception e) {
				log.error("服务器【{}】查询云资源失败：{}", id, e.getMessage());
			}
			return res;
		}).findFirst().orElse(null);
		if (cloud != null) {
			throw new ParamException("030215", "当前服务器存在云平台资源");
		}

		try {
			iaasDao.deleteById(iaas.getId());
			nodeDao.deleteById(iaas.getDeviceId());
		} catch (BaseException e) {
			log.error("资源删除失败");
			throw new BaseException(AssetErrorCode.RESOURSE_DB_DELETE);
		}

		// TODO 删除模拟数据
		// String key = String.format("mesh_controller_mock_type_%d_id_node_%s",
		// MockType.IT_DEVICE.getType(), iaas.getId());
		// mockNodeRedis.delete(key);

		return iaas;
	}

	@Transactional
	@Override
	public IaasEntity deleteSwitcher(String id, String userId) throws BaseException {
		// TODO Auto-generated method stub
		IaasEntity iaas = iaasDao.getById(id, userId);
		if (iaas == null) {
			throw new ParamException(AssetErrorCode.RESOURSE_NOT_EXIST);
		}

		try {
			iaasDao.deleteById(iaas.getId());
			switcherDao.deleteById(iaas.getDeviceId());
		} catch (BaseException e) {
			log.error("资源删除失败");
			throw new BaseException(AssetErrorCode.RESOURSE_DB_DELETE);
		}

		// TODO 删除模拟数据
		// String key =
		// String.format("mesh_controller_mock_type_%d_id_switcher_%s",
		// MockType.IT_DEVICE.getType(), iaas.getId());
		// mockNodeRedis.delete(key);

		return iaas;
	}

	@Override
	public List<DeviceItemVo> listDevice(ListDeviceMsg msg) throws BaseException {
		// TODO Auto-generated method stub
		Map<String, Object> props = new HashMap<String, Object>();
		if (msg.getFrom() != null) {
			props.put("from", msg.getFrom());
		}
		if (msg.getDatacenterId() != null) {
			props.put("datacenterId", msg.getDatacenterId());
		}
		if (msg.getType() != null) {
			props.put("type", msg.getType());
		}
		List<DeviceItemVo> devices = iaasDao.findByProperties(props, DeviceItemVo.class);
		return devices;
	}

	@Override
	public int countDatacenter() throws BaseException {
		return datacenterDao.count();
	}

	@Override
	public CountDeviceVo countDevice(String datacenterId) throws BaseException {

		CountDeviceVo vo = new CountDeviceVo();
		ListDeviceMsg msg = new ListDeviceMsg();
		msg.setDatacenterId(datacenterId);
		int total;

		msg.setType(0);
		int generalNum = this.listDevice(msg).size();

		msg.setType(1);
		int airConditionNum = this.listDevice(msg).size();

		msg.setType(2);
		int upsNum = this.listDevice(msg).size();

		msg.setType(3);
		int pduNum = this.listDevice(msg).size();

		msg.setType(4);
		int temperatureSensorNum = this.listDevice(msg).size();

		msg.setType(5);
		int cabinetNum = this.listDevice(msg).size();

		msg.setType(6);
		int serverNum = this.listDevice(msg).size();

		msg.setType(7);
		int switcherNum = this.listDevice(msg).size();

		msg.setType(8);
		int distributionBoxNum = this.listDevice(msg).size();

		total = generalNum + airConditionNum + upsNum + pduNum + temperatureSensorNum + cabinetNum + serverNum
				+ switcherNum + distributionBoxNum;

		vo.setGeneralNum(generalNum);
		vo.setAirConditionNum(airConditionNum);
		vo.setUpsNum(upsNum);
		vo.setPduNum(pduNum);
		vo.setTemperatureSensorNum(temperatureSensorNum);
		vo.setCabinetNum(cabinetNum);
		vo.setServerNum(serverNum);
		vo.setSwitcherNum(switcherNum);
		vo.setDistributionBoxNum(distributionBoxNum);

		vo.setTotal(total);

		return vo;
	}

	@Override
	public DeviceItemVo getDeviceByDeviceId(String deviceId) throws BaseException {
		// TODO Auto-generated method stub
		DeviceItemVo vo = null;
		IaasEntity iaas = iaasDao.findUniqueByProperty("deviceId", deviceId);
		if (iaas != null) {
			vo = new DeviceItemVo();
			BeanUtils.copyProperties(iaas, vo);
		}

		return vo;
	}

	@Override
	public List<DatacenterItemVo> listDatacenter(ListDatacenterMsg msg) throws BaseException {
		// TODO Auto-generated method stub
		return datacenterDao.findAll(DatacenterItemVo.class);
	}

	public String syncDevice() {

		List<AuthorityVo> authorities = iaasDao.listAuthority(AuthorityResourceClassification.IAAS.getName());

		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
				.collect(Collectors.toList());
		List<String> allowAuthorities = authorities.stream().filter(s -> !filterAuthorities.contains(s.getId()))
				.map(s -> s.getId()).collect(Collectors.toList());
		String templateAll = "空调,配电箱,UPS设备同步成功!";
		String templatePart = "%s设备同步成功！%s设备同步失败，请开启设备权限!";
		String templateNone = "空调,配电箱,UPS设备同步失败，请开启设备权限!";
		String failContent = "";
		String successContent = "";
		for (String id : filterAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			failContent = failContent + deviceType.getCnName() + ",";
		}
		for (String id : allowAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			successContent = successContent + deviceType.getCnName() + ",";
		}

		syncDeviceSupervision();
		
		List<MockIaasVo> res = mockIaasRedis.getByType(MockType.IAAS);
		List<String> exists = iaasDao.findAll().stream().filter(s -> {
			if (DeviceType.SERVER.equals(DeviceType.getDeviceTypeByNo(s.getType()))
					&& DeviceType.SWITCHER.equals(DeviceType.getDeviceTypeByNo(s.getType()))) {
				return false;
			}
			return true;
		}).map(s -> s.getId()).collect(Collectors.toList());
		if (res != null) {
			for (MockIaasVo r : res) {
				if (!exists.contains(r.getId())) {
					String id = DeviceType.getDeviceTypeByNo(r.getType()).getName();
					if (filterAuthorities.contains(id)) {
						continue;
					}
					IaasEntity iaas = new IaasEntity();
					BeanUtils.copyProperties(r, iaas);
					iaas.setFrom(ResourceSourceType.SYNC.getName());
					iaas.setCreateTime(TimestampUtil.strToDate(r.getCreateTime(), "yyyy/MM/dd HH:mm:ss"));
					iaas.setVisible(authorityMap.get(r.getType()));
					try {
						iaasDao.save(iaas);
					} catch (Exception e) {
						log.error("数据库保存失败：{}", e.getMessage());
					}
				}
			}
		}
		if (filterAuthorities.size() == 3) {
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			LogUtil.log(request, templateNone);
			throw new BaseException("000000", templateNone);
		}
		if (filterAuthorities.size() > 0 && filterAuthorities.size() < 3 && StringUtils.isNotBlank(successContent)
				&& StringUtils.isNotBlank(failContent)) {
			String content = String.format(templatePart, successContent.substring(0, successContent.length() - 1),
					failContent.substring(0, failContent.length() - 1));

			return content;
		}
		return templateAll;
	}

	public String syncNodeSwitcher() {

//		List<AuthorityVo> authorities = iaasDao.listAuthority(AuthorityResourceClassification.IT_DEVICE.getName());
//		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
//				.collect(Collectors.toList());
//		List<String> allowAuthorities = authorities.stream().filter(s -> !filterAuthorities.contains(s.getId()))
//				.map(s -> s.getId()).collect(Collectors.toList());
//
//		String templateAll = "服务器，交换机同步成功!";
//		String templatePart = "%s同步成功！%s同步失败，请开启设备权限!";
//		String templateNone = "服务器交换机同步失败，请开启设备权限!";
//		String failContent = "";
//		String successContent = "";
//
//		for (String id : filterAuthorities) {
//			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
//			failContent = failContent + deviceType.getCnName() + ",";
//		}
//		for (String id : allowAuthorities) {
//			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
//			successContent = successContent + deviceType.getCnName() + ",";
//		}
//
//		String nodeKey = String.format("mesh_controller_mock_type_%d_id_node_*", MockType.IT_DEVICE.getType());
//		String switcherKey = String.format("mesh_controller_mock_type_%d_id_switcher_*", MockType.IT_DEVICE.getType());
//		List<MockNodeVo> redisNodes = mockNodeRedis.getByType(nodeKey);
//		List<MockSwitcherVo> redisSwitchers = mockSwitcherRedis.getByType(switcherKey);
//		List<String> nodeExists = iaasDao.findAll().stream()
//				.filter(s -> DeviceType.SERVER.equals(DeviceType.getDeviceTypeByNo(s.getType()))).map(s -> s.getId())
//				.collect(Collectors.toList());
//		List<String> switcherExists = iaasDao.findAll().stream()
//				.filter(s -> DeviceType.SWITCHER.equals(DeviceType.getDeviceTypeByNo(s.getType()))).map(s -> s.getId())
//				.collect(Collectors.toList());
//		if (redisNodes != null) {
//			for (MockNodeVo r : redisNodes) {
//				if (!nodeExists.contains(r.getId())
//						&& DeviceType.SERVER.equals(DeviceType.getDeviceTypeByNo(r.getType()))) {
//					String id = DeviceType.getDeviceTypeByNo(r.getType()).getName();
//					if (filterAuthorities.contains(id)) {
//						continue;
//					}
//					IaasEntity iaas = new IaasEntity();
//					NodeEntity node = new NodeEntity();
//					BeanUtils.copyProperties(r, iaas);
//					BeanUtils.copyProperties(r, node);
//					node.setId(iaas.getDeviceId());
//					iaas.setFrom(ResourceSourceType.SYNC.getName());
//					iaas.setCreateTime(TimestampUtil.strToDate(r.getCreateTime(), "yyyy/MM/dd HH:mm:ss"));
//					iaas.setVisible(authorityMap.get(r.getType()));
//					try {
//						iaasDao.save(iaas);
//						nodeDao.save(node);
//					} catch (Exception e) {
//						log.error("数据库保存失败：{}", e.getMessage());
//					}
//				}
//			}
//		}
//		if (redisSwitchers != null) {
//			for (MockSwitcherVo r : redisSwitchers) {
//				if (!switcherExists.contains(r.getId())
//						&& DeviceType.SWITCHER.equals(DeviceType.getDeviceTypeByNo(r.getType()))) {
//					String id = DeviceType.getDeviceTypeByNo(r.getType()).getName();
//					if (filterAuthorities.contains(id)) {
//						continue;
//					}
//					IaasEntity iaas = new IaasEntity();
//					SwitcherEntity switcher = new SwitcherEntity();
//					BeanUtils.copyProperties(r, iaas);
//					BeanUtils.copyProperties(r, switcher);
//					switcher.setId(iaas.getDeviceId());
//					iaas.setCreateTime(TimestampUtil.strToDate(r.getCreateTime(), "yyyy/MM/dd HH:mm:ss"));
//					iaas.setFrom(ResourceSourceType.SYNC.getName());
//					iaas.setVisible(authorityMap.get(r.getType()));
//					try {
//						iaasDao.save(iaas);
//						switcherDao.save(switcher);
//					} catch (Exception e) {
//						log.error("数据库保存失败：{}", e.getMessage());
//					}
//
//				}
//			}
//		}
//
//		if (filterAuthorities.size() == 2) {
//			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
//			LogUtil.log(request, templateNone);
//			throw new BaseException("000000", templateNone);
//		}
//
//		voltageFmService.SyncVoltageFm();
//
//		if (filterAuthorities.size() == 1) {
//			String content = String.format(templatePart, successContent.substring(0, successContent.length() - 1),
//					failContent.substring(0, failContent.length() - 1));
//			return content;
//		}
//		return templateAll;
		return syncNodeSwitcherFromL2System();
	}

	public PageResult<DeviceItemVo> pageItDevice(int pageNum, int pageSize, String name, String userId) {
		PageResult<DeviceItemVo> iaases = iaasDao.pageNodeAndSwitcher(pageNum, pageSize, name, userId,
				DeviceItemVo.class);
		for (DeviceItemVo vo : iaases.getList()) {
			vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
		}
		PageResult<DeviceItemVo> result = new PageResult<DeviceItemVo>();
		result.setList(iaases.getList());
		result.setPageNo(iaases.getPageNo());
		result.setPageSize(iaases.getPageSize());
		result.setTotalCount(iaases.getTotalCount());
		return result;
	}

	public PageResult<DeviceItemVo> pageItDevice(int pageNum, int pageSize, String datacenterId, String name,
			Integer type) {
		PageResult<DeviceItemVo> iaases = iaasDao.pageItDevice(pageNum, pageSize, datacenterId, name, type);
		for (DeviceItemVo vo : iaases.getList()) {
			vo.setTypeCnName(DeviceType.getDeviceTypeByNo(vo.getType()).getCnName());
			vo.setDatacenterName(datacenterNameMap.get(vo.getDatacenterId()));
		}
		PageResult<DeviceItemVo> result = new PageResult<DeviceItemVo>();
		result.setList(iaases.getList());
		result.setPageNo(iaases.getPageNo());
		result.setPageSize(iaases.getPageSize());
		result.setTotalCount(iaases.getTotalCount());
		return result;
	}

	@Override
	public PageResult<DatacenterItemVo> pageDatacenter(int pageNum, int pageSize, String name, String ip, String userId)
			throws BaseException {
		// TODO Auto-generated method stub
		PageResult<DatacenterItemVo> result = datacenterDao.page(pageNum, pageSize, null, name, ip, userId, null,
				DatacenterItemVo.class);
		return result;
	}

	@Override
	public DatacenterItemVo getDatacenter(String id) {
		DatacenterItemVo vo = new DatacenterItemVo();
		DatacenterEntity entity = datacenterDao.getById(id);
		vo.setCreateTime(entity.getCreateTime());
		vo.setId(entity.getId());
		vo.setCreator(entity.getCreator());
		vo.setIp(entity.getIp());
		vo.setIsScheduler(entity.getIsScheduler());
		vo.setName(entity.getName());
		vo.setPower(entity.getPower());
		vo.setPowerConservation(entity.getPowerConservation());
		vo.setThreshold(entity.getThreshold());

		return vo;
	}

	@Override
	public List<NodeItemVo> listNode(String datacenterId, String userId) throws BaseException {
		// TODO Auto-generated method stub
		List<NodeItemVo> nodes = iaasDao.listNode(datacenterId, null);
		if (nodes != null) {
			for (NodeItemVo vo : nodes) {
				DeviceType type = DeviceType.getDeviceTypeByNo(vo.getType());
				if (type != null) {
					vo.setTypeCnName(type.getCnName());
				}
				NetworkStatus networkStatus = NetworkStatus.getStatusByNo(vo.getNetworkStatus());
				if (networkStatus != null) {
					vo.setNetworkStatusCnName(networkStatus.getCnName());
				}
				PowerStatus powerStatus = PowerStatus.getStatusByNo(vo.getPowerStatus());
				if (powerStatus != null) {
					vo.setPowerStatusCnName(powerStatus.getCnName());
				}

			}
		}
		return nodes;
	}

	@Override
	public List<DeviceItemVo> listDevice(String datacenterId, Integer type, String userId) throws BaseException {
		// TODO Auto-generated method stub
		if (DeviceType.getDeviceTypeByNo(type) == null) {
			throw new BaseException();
		}
		List<DeviceItemVo> devices = iaasDao.listDevice(datacenterId, type, null, DeviceItemVo.class);
		return null;
	}

	// private String encryptSm4Save(String clientCipherSm4, String userId) {
	// log.info("[AssetServiceImpl][encryptSm4Save] 接收客户端的SM4密文：{}",
	// clientCipherSm4);
	// String cipher = null;
	// try {
	// String data = smService.decryptClientSm4(clientCipherSm4, userId);
	// log.info("[SM][AssetServiceImpl][encryptSm4Save] SM4解密客户端密文得到明文：{}",
	// data);
	// cipher = smService.encryptServerSm4(data, userId);
	// log.info("[SM][AssetServiceImpl][encryptSm4Save] SM4加密存储到数据库中的密文： {}",
	// cipher);
	//
	// }catch (Exception e) {
	// log.error("[SM][AssetServiceImpl][encryptSm4ToClient] 国密加解密异常：{}",
	// e.getMessage());
	// }
	// return cipher;
	// }

	/**
	 * 一次一密
	 * 
	 * @param data
	 * @param userId
	 * @return
	 */
	private String encryptSm4SaveDb(String data, String userId) {
		String cipher = null;
		try {
			String SM3Key = smService.encryptSm3(data, userId);
			String newData = data + SM3Key;
			cipher = smService.encryptServerSm4(newData, userId);

			log.info("[SM][AssetServiceImpl][encryptSm4SaveDb] SM4加密存储到数据库中的密文： {}", cipher);

		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][encryptSm4SaveDb] 国密加解密异常：{}", e.getMessage());
		}
		return cipher;
	}

	// private String encryptSm4ToClient(String serverCipherSm4, String userId)
	// {
	// log.info("[AssetServiceImpl][encryptSm4ToClient] 获取数据库中SM4密文：{}",
	// serverCipherSm4);
	// String cipher = null;
	// try {
	// String data = smService.decryptServerSm4(serverCipherSm4, userId);
	// log.info("[SM][AssetServiceImpl][encryptSm4ToClient] SM4解密数据库密文得到明文：{}",
	// data);
	// cipher = smService.encryptClientSm4(data, userId);
	// log.info("[SM][AssetServiceImpl][encryptSm4ToClient] SM4发送到客户端的密文：{}",
	// cipher);
	//
	// }catch (Exception e) {
	// log.error("[AssetServiceImpl][encryptSm4ToClient] 国密加解密异常：{}",
	// e.getMessage());
	// }
	// return cipher;
	// }

	/**
	 * 一次一密
	 * 
	 * @param cipher
	 * @param userId
	 * @return
	 */
	private String decryptSm4FromDb(String cipher, String userId) {
		log.info("[AssetServiceImpl][encryptSm4ToClient] 获取数据库中SM4密文：{}", cipher);
		String data = null;
		try {
			data = smService.decryptServerSm4(cipher, userId);
			log.info("[SM][AssetServiceImpl][encryptSm4ToClient] SM4解密数据库密文得到明文：{}", data);
		} catch (Exception e) {
			log.error("[AssetServiceImpl][encryptSm4ToClient] 国密加解密异常：{}", e.getMessage());
		}
		return data;
	}

	@Override
	public String createNode(CreateNodeSmMsg msg, String userId, HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub
		// 国密处理
		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher) && StringUtils.isNotBlank(msg.getSmData())) {
			// 解密客户端密文
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {
				String data = decryptFromClient(sm4Key, msg.getSmData(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String SM3Key = data.substring(len - 64, len);
					String smData = data.substring(0, len - 64);
					// 加密数据保存到数据库
					msg.setSmData(encryptSm4SaveDb(smData, userId));
					if (!sm3Verify(SM3Key, smData, userId)) {
						log.info("[SM][AssetServiceImpl][createNode] 数据完整性被破坏，存在被篡改风险【{}】", msg.getName());
						throw new ParamException(null, "完整性被破坏, 请注意数据安全");
					}
				} else {
					throw new ParamException(null, "完整性被破坏, 请注意数据安全");
				}
			}

		} else {
			// log.error("[SM][AssetServiceImpl][createNode] 客户端秘钥解密失败");
			// throw new ParamException(null, "完整性被破坏, 请注意数据安全");
		}

		return createNode(msg, userId);
	}

	@Override
	public String updateNode(UpdateNodeSmMsg msg, String userId, HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub

		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher) && StringUtils.isNotBlank(msg.getSmData())) {
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {

				String data = decryptFromClient(sm4Key, msg.getSmData(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String SM3Key = data.substring(len - 64, len);
					String smData = data.substring(0, len - 64);
					// 加密数据保存到数据库
					msg.setSmData(encryptSm4SaveDb(smData, userId));
					if (!sm3Verify(SM3Key, smData, userId)) {
						log.info("[SM][AssetServiceImpl][updateNode] 数据完整性被破坏，存在被篡改风险【{}】", msg.getName());
						throw new ParamException(null, "完整性被破坏, 请注意数据安全");
					}
				} else {
					throw new ParamException(null, "完整性被破坏, 请注意数据安全");
				}

			}
		} else {
			// log.error("[SM][AssetServiceImpl][updateNode] 客户端秘钥解密失败");
			// throw new ParamException(null, "完整性被破坏, 请注意数据安全");
		}
		return updateNode(msg, userId);
	}

	@Override
	public NodeItemVo detailNode(String id, String userId, HttpServletRequest request, HttpServletResponse response)
			throws BaseException {
		// TODO Auto-generated method stub
		NodeItemVo vo = detailNode(id, userId);
		// 国密处理
		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher)) {
			// 解密客户端密文
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {
				String data = decryptSm4FromDb(vo.getSmData(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String sm3Key = data.substring(len - 64, len);
					String smData = data.substring(0, len - 64);
					// 加密数据保存到数据库
					String cipher = encryptToClient(sm3Key, sm4Key, smData, userId);
					vo.setSmData(cipher);
					if (!sm3Verify(sm3Key, smData, userId)) {
						log.info("[SM][AssetServiceImpl][detailNode] SM3解密，数据完整性被破坏，存在被篡改风险{}【{}】", vo.getName(),
								vo.getId());
						vo.setSmData(null);
						// PermissionsInfoVo permissionVo = getUrl(request);
						// if(permissionVo != null) {
						// sysBaseAPI.addLog(permissionVo.getName()+"（完整性被破坏,
						// 请注意数据安全）", SysLogType.OPERATE,
						// SysLogOperateType.DETAIL, null,
						// SysLogUrlOperate.errorRemark,
						// request.getParameter("title"));
						// }
						LogUtil.log(request, SysLogUrlOperate.errorSecurity);
					}
				} else {
					log.info("[SM][AssetServiceImpl][detailNode] SM4解密，数据完整性被破坏，存在被篡改风险{}【{}】", vo.getName(),
							vo.getId());
					vo.setSmData(null);
					// PermissionsInfoVo permissionVo = getUrl(request);
					// if(permissionVo != null) {
					// sysBaseAPI.addLog(permissionVo.getName()+"（完整性被破坏,
					// 请注意数据安全）", SysLogType.OPERATE, SysLogOperateType.DETAIL,
					// null, SysLogUrlOperate.errorRemark,
					// request.getParameter("title"));
					// }
					LogUtil.log(request, SysLogUrlOperate.errorSecurity);
				}
			}
		}

		return vo;
	}

	@Override
	public String createSwitcher(CreateSwitcherMsg msg, String userId, HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub
		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher) && StringUtils.isNotBlank(msg.getCommunity())) {
			// 解密客户端密文
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {
				String data = decryptFromClient(sm4Key, msg.getCommunity(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String sm3Key = data.substring(len - 64, len);
					String community = data.substring(0, len - 64);
					// 加密数据保存到数据库
					msg.setCommunity(encryptSm4SaveDb(community, userId));
					if (!sm3Verify(sm3Key, community, userId)) {
						log.info("[SM][AssetServiceImpl][createNode] 数据完整性被破坏，存在被篡改风险【{}】", msg.getName());
						throw new ParamException(null, "完整性被破坏, 请注意数据安全");
					}
				} else {
					throw new ParamException(null, "完整性被破坏, 请注意数据安全");
				}
			}
		} else {
			// log.error("[SM][AssetServiceImpl][createSwitcher] 客户端解密失败");
			// throw new ParamException(null, "完整性被破坏, 请注意数据安全");
		}
		return createSwitcher(msg, userId);
	}

	@Override
	public String updateSwitcher(UpdateSwitcherMsg msg, String userId, HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub
		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher) && StringUtils.isNotBlank(msg.getCommunity())) {

			// 解密客户端密文
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {
				String data = decryptFromClient(sm4Key, msg.getCommunity(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String sm3Key = data.substring(len - 64, len);
					String community = data.substring(0, len - 64);
					// 加密数据保存到数据库
					msg.setCommunity(encryptSm4SaveDb(community, userId));
					if (!sm3Verify(sm3Key, community, userId)) {
						log.info("[SM][AssetServiceImpl][updateSwitcher] 数据完整性被破坏，存在被篡改风险【{}】", msg.getName());
						throw new ParamException(null, "完整性被破坏, 请注意数据安全");
					}
				} else {
					throw new ParamException(null, "完整性被破坏, 请注意数据安全");
				}
			}

		} else {
			// log.error("[SM][AssetServiceImpl][updateSwitcher] 客户端解密失败");
			// throw new ParamException(null, "完整性被破坏, 请注意数据安全");
		}
		return updateSwitcher(msg, userId);
	}

	@Override
	public SwitcherItemVo detailSwitcher(String id, String userId, HttpServletRequest request,
			HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub

		SwitcherItemVo vo = detailSwitcher(id, userId);
		// 国密处理
		String sm2Cipher = request.getHeader(SM_TOKEN);
		if (StringUtils.isNotBlank(sm2Cipher)) {
			// 解密客户端密文
			String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
			if (sm4Key != null) {
				String data = decryptSm4FromDb(vo.getCommunity(), userId);
				if (data != null && data.length() > 64) {
					int len = data.length();
					String sm3Key = data.substring(len - 64, len);
					String community = data.substring(0, len - 64);
					String cipher = encryptToClient(sm3Key, sm4Key, community, userId);
					vo.setCommunity(cipher);

					// 检测数据完整性
					if (!sm3Verify(sm3Key, community, userId)) {
						log.info("[SM][AssetServiceImpl][detailSwitcher] SM3解密，数据完整性被破坏，存在被篡改风险{}【{}】", vo.getName(),
								vo.getId());
						vo.setCommunity(null);
						PermissionsInfoVo permissionVo = getUrl(request);
						if (permissionVo != null) {
							sysBaseAPI.addLog(permissionVo.getName() + "（完整性被破坏, 请注意数据安全）", SysLogType.OPERATE,
									SysLogOperateType.DETAIL, null, SysLogUrlOperate.errorRemark,
									request.getParameter("title"));
						}
					}

				} else {
					log.info("[SM][AssetServiceImpl][detailSwitcher] SM4解密, 数据完整性被破坏，存在被篡改风险{}【{}】", vo.getName(),
							vo.getId());
					vo.setCommunity(null);
					PermissionsInfoVo permissionVo = getUrl(request);
					if (permissionVo != null) {
						sysBaseAPI.addLog(permissionVo.getName() + "（完整性被破坏, 请注意数据安全）", SysLogType.OPERATE,
								SysLogOperateType.DETAIL, null, SysLogUrlOperate.errorRemark,
								request.getParameter("title"));
					}

				}
			}
		}
		return vo;
	}

	/**
	 * sm2解密
	 * 
	 * @param sm2Cipher
	 * @param userId
	 * @return
	 */
	private String decryptSm2FromClient(String sm2Cipher, String userId) {
		String smKey = null;
		try {
			smKey = smService.decryptSm2(sm2Cipher, userId);
		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][decryptSm2FromClient] 解密失败");
		}
		return smKey;
	}
	//
	// /**
	// * sm2解密混合秘钥sm3、sm4
	// * @param sm2Cipher
	// * @param sep
	// * @param userId
	// * @return
	// */
	// private String[] decryptSm2FromClient(String sm2Cipher, String sep,
	// String userId) {
	// String[] smKey = null;
	// try {
	// String data = smService.decryptSm2(sm2Cipher, userId);
	// if(sep == null) {
	// smKey = new String[] {data};
	// }else {
	// smKey = data.split(sep);
	// }
	// }catch(Exception e ) {
	// log.error("[SM][AssetServiceImpl][decryptSm2FromClient] 解密失败");
	// }
	// if(sep != null && smKey.length > 1) {
	// return smKey;
	// }
	// return null;
	// }

	/**
	 * 一次一密
	 * 
	 * @param key
	 * @param sm2Cipher
	 * @param cipher
	 * @param userId
	 * @return
	 */
	private String decryptFromClient(String sm4Key, String cipher, String userId) {
		String data = "";
		try {
			data = smService.decryptClientSm4(sm4Key, cipher, userId);
		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][encryptFromClient] 解密失败");
		}
		return data;
	}

	/**
	 * 一次一密
	 * 
	 * @param sm4Key
	 * @param data
	 * @param userId
	 * @return
	 */
	private String encryptToClient(String sm3Key, String sm4Key, String data, String userId) {
		String cipher = "";
		try {
			String newData = data + sm3Key;
			cipher = smService.encryptClientSm4(sm4Key, newData, userId);
		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][encryptToClient] 加密失败");
		}
		return cipher;
	}

	/**
	 * sm3 验证
	 * 
	 * @param key
	 * @param data
	 * @param userId
	 * @return
	 */
	private boolean sm3Verify(String key, String data, String userId) {
		boolean res = false;
		try {
			res = smService.verifySm3(data, key);
		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][sm3Verify] SM3 加密异常：{}", e.getMessage());
		}
		return res;
	}

	private String setSm3Header(String content, String userId, HttpServletRequest request,
			HttpServletResponse response) {
		String digest = null;
		try {
			digest = smService.encryptSm3(content, userId);
			log.info("[SM][AssetServiceImpl][setSm3Header] SM3对数据【{}】，加密生成发送到客户端的信息摘要：{}", content, digest);
		} catch (Exception e) {
			log.error("[SM][AssetServiceImpl][setSm3Header] SM3 加密异常：{}", e.getMessage());
		}
		response.setHeader(SmManager.SM3_HEADER, digest);
		return digest;
	}

	private void setSm3Header(String sm3Key, HttpServletRequest request, HttpServletResponse response) {
		response.setHeader(SmManager.SM3_HEADER, sm3Key);
	}

	@Override
	public PageResult<SwitcherItemVo> pageSwitcher(int pageNum, int pageSize, String name, String userId,
			HttpServletRequest request, HttpServletResponse response) throws BaseException {
		// TODO Auto-generated method stub
		PageResult<SwitcherItemVo> res = pageSwitcher(pageNum, pageSize, name, userId);
		if (res != null) {
			String sm2Cipher = request.getHeader(SM_TOKEN);
			if (StringUtils.isNotBlank(sm2Cipher)) {
				String sm4Key = decryptSm2FromClient(sm2Cipher, userId);
				if (sm4Key != null) {
					for (SwitcherItemVo vo : res.getList()) {
						// 国密处理
						String data = decryptSm4FromDb(vo.getCommunity(), userId);
						if (data != null && data.length() > 64) {
							int len = data.length();
							String sm3Key = data.substring(len - 64, len);
							String community = data.substring(0, len - 64);
							String cipher = encryptToClient(sm3Key, sm4Key, community, userId);
							vo.setCommunity(cipher);
							if (!sm3Verify(sm3Key, community, userId)) {
								log.info("[SM][AssetServiceImpl][pageSwitcher] SM3解密，数据完整性被破坏，存在被篡改风险{}【{}】",
										vo.getName(), vo.getId());
								vo.setCommunity(null);
								PermissionsInfoVo permissionVo = getUrl(request);
								if (permissionVo != null) {
									sysBaseAPI.addLog(permissionVo.getName() + "（完整性被破坏, 请注意数据安全）", SysLogType.OPERATE,
											SysLogOperateType.DETAIL, null, SysLogUrlOperate.errorRemark,
											request.getParameter("title"));
								}
							}
						} else {
							log.info("[SM][AssetServiceImpl][pageSwitcher] SM3解密，数据完整性被破坏，存在被篡改风险{}【{}】", vo.getName(),
									vo.getId());
							vo.setCommunity(null);
							PermissionsInfoVo permissionVo = getUrl(request);
							if (permissionVo != null) {
								sysBaseAPI.addLog(permissionVo.getName() + "（完整性被破坏, 请注意数据安全）", SysLogType.OPERATE,
										SysLogOperateType.DETAIL, null, SysLogUrlOperate.errorRemark,
										request.getParameter("title"));
							}
						}
					}

				}
			}
		}
		return res;
	}

	@Scheduled(initialDelay = 30 * 1000, fixedDelay = 60 * 1000)
	public void cacheDatacenter() {
		List<DatacenterItemVo> datacenters = datacenterDao.findAll(DatacenterItemVo.class);
		if (datacenters != null) {
			for (DatacenterItemVo vo : datacenters) {
				datacenterNameMap.put(vo.getId(), vo.getName());
				datacenterMap.put(vo.getId(), vo);
				// performanceDevices = iaasDao.page(1, 10, null, null, null,
				// null, DeviceItemVo.class).getList();
			}
			List<String> datacenterIds = datacenters.stream().map( s -> s.getId()).collect(Collectors.toList());
			redisUtil.set("mesh_asset_datacenters", datacenterIds);
		}

//		updatePerformanceStatus();
	}

	public void updatePerformanceStatus() {
		try {
			boolean result = (boolean) redisUtil.get(PERFORMANCE);
			if (result) {
				log.info("高性能模式开启");
				isPerformance = true;
			} else {
				log.info("高性能模式关闭");
				isPerformance = false;
			}
		} catch (Exception e) {
			log.info("高性能模式关闭");
			isPerformance = false;
		}
	}

	@Scheduled(initialDelay = 30 * 1000, fixedDelay = 2 * 1000)
	public void updateAuthorityStatus() {
		try {
			List<AuthorityVo> iaasRes = authorityDao.listByClassification("iaas", AuthorityVo.class);
			for(AuthorityVo item: iaasRes) {
	    		int typeNo = DeviceType.getDeviceTypeByName(item.getId()).getNo();
	    		if(authorityMap.get(typeNo) != null && authorityMap.get(typeNo) != item.getEnabled()) {
	    			authorityMap.put(typeNo, item.getEnabled());
	    			iaasDao.updateBatchVisiable(item.getEnabled(), typeNo);
	    		}
	    		if(authorityMap.get(typeNo) == null) {
	    			authorityMap.put(typeNo, item.getEnabled());
	    		}
			}
		} catch (Exception e) {
			log.error("[AuthorityService][set] iaasDao iaas visible 更新失败{}", e.getMessage());
		}
		try {
			List<AuthorityVo> deviceRes = authorityDao.listByClassification("device", AuthorityVo.class);
			for(AuthorityVo item: deviceRes) {
	    		int typeNo = DeviceType.getDeviceTypeByName(item.getId()).getNo();
	    		if(authorityMap.get(typeNo) != null && authorityMap.get(typeNo) != item.getEnabled()) {
	    			authorityMap.put(typeNo, item.getEnabled());
	    			iaasDao.updateBatchVisiable(item.getEnabled(), typeNo);
	    		}
	    		if(authorityMap.get(typeNo) == null) {
	    			authorityMap.put(typeNo, item.getEnabled());
	    		}
			}
		} catch (Exception e) {
			log.error("[AuthorityService][set] iaasDao server and switcher visible 更新失败{}", e.getMessage());
		}
	}
	
	private String[] strSplit(String data, String sep) {
		String[] strs = data.split(sep);
		if (strs.length > 1) {
			return strs;
		}
		return null;
	}

	private PermissionsInfoVo getUrl(HttpServletRequest request) {
		String requestUrl = request.getRequestURI().replace("//", "/");
		if (requestUrl.startsWith("/mesh-controller")) {
			requestUrl = requestUrl.substring("/mesh-controller".length(), requestUrl.length());
		}
		PermissionsInfoVo vo = PermissionCodeCache.getByUrl(requestUrl);
		return vo;
	}

	public String syncDeviceSupervision() {

		List<AuthorityVo> authorities = iaasDao.listAuthority(AuthorityResourceClassification.IAAS.getName());

		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
				.collect(Collectors.toList());
		List<String> allowAuthorities = authorities.stream().filter(s -> !filterAuthorities.contains(s.getId()))
				.map(s -> s.getId()).collect(Collectors.toList());
		String templateAll = "空调,配电箱,UPS设备同步成功!";
		String templatePart = "%s设备同步成功！%s设备同步失败，请开启设备权限!";
		String templateNone = "空调,配电箱,UPS设备同步失败，请开启设备权限!";
		String failContent = "";
		String successContent = "";
		for (String id : filterAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			failContent = failContent + deviceType.getCnName() + ",";
		}
		for (String id : allowAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			successContent = successContent + deviceType.getCnName() + ",";
		}

		for(String id: allowAuthorities) {
			supervision.syncDevice(DeviceType.getDeviceTypeByName(id).getNo());
		}
		
		if (filterAuthorities.size() == 3) {
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			LogUtil.log(request, templateNone);
			throw new BaseException("000000", templateNone);
		}
		if (filterAuthorities.size() > 0 && filterAuthorities.size() < 3 && StringUtils.isNotBlank(successContent)
				&& StringUtils.isNotBlank(failContent)) {
			String content = String.format(templatePart, successContent.substring(0, successContent.length() - 1),
					failContent.substring(0, failContent.length() - 1));

			return content;
		}
		return templateAll;
	}
	
	public String syncNodeSwitcherFromL2System() {

		List<AuthorityVo> authorities = iaasDao.listAuthority(AuthorityResourceClassification.IT_DEVICE.getName());
		List<String> filterAuthorities = authorities.stream().filter(s -> !s.getEnabled()).map(s -> s.getId())
				.collect(Collectors.toList());
		List<String> allowAuthorities = authorities.stream().filter(s -> !filterAuthorities.contains(s.getId()))
				.map(s -> s.getId()).collect(Collectors.toList());

		String templateAll = "服务器，交换机同步成功!";
		String templatePart = "%s同步成功！%s同步失败，请开启设备权限!";
		String templateNone = "服务器交换机同步失败，请开启设备权限!";
		String failContent = "";
		String successContent = "";

		for (String id : filterAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			failContent = failContent + deviceType.getCnName() + ",";
		}
		for (String id : allowAuthorities) {
			DeviceType deviceType = DeviceType.getDeviceTypeByName(id);
			successContent = successContent + deviceType.getCnName() + ",";
		}

		for(String id: allowAuthorities) {
			if(DeviceType.SERVER.getName().equals(id)) {
				syncL2System.syncNode();
			}else if (DeviceType.SWITCHER.getName().equals(id)) {
				syncL2System.syncSwitcher();
			}
		}

		if (filterAuthorities.size() == 2) {
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			LogUtil.log(request, templateNone);
			throw new BaseException("000000", templateNone);
		}

		voltageFmService.syncDvfsByService();

		if (filterAuthorities.size() == 1) {
			String content = String.format(templatePart, successContent.substring(0, successContent.length() - 1),
					failContent.substring(0, failContent.length() - 1));
			return content;
		}
		return templateAll;
	}
}
